//
//  MKMapView+Extension.swift
//  ImGuider X
//
//  Created by 陆涛 on 2018/10/25.
//  Copyright © 2018 imguider. All rights reserved.
//

import UIKit
import MapKit

extension MKMapView {
    
    func addLine(to coor:CLLocationCoordinate2D,complete:@escaping((String?)->Void)) -> Bool {
        
        let distance = LocationManager.distance(form: coor, to: coorSelf)
        
        if distance < 10 {
            
            removeAllOverlays()
            return true
        }
        
        if distance > 3000 {
             removeAllOverlays()
            return false
        }
        
        let fromPM = MKPlacemark(coordinate: coorSelf, addressDictionary: nil)
        let toPM = MKPlacemark(coordinate: coor, addressDictionary: nil)
        
        let request = MKDirections.Request()
        request.source = MKMapItem(placemark: fromPM)
        request.destination = MKMapItem(placemark: toPM)
        request.transportType = .walking
        
        let directions = MKDirections(request: request)
        
        directions.calculate {
            
            [weak self] response, error in
            guard let `self` = self else { return }
            
            self.removeAllOverlays()
            
            if let error = error {
                
                complete(error.localizedDescription)
                return
            }
            
            if let polyline = response?.routes.first?.polyline {
                
                self.addOverlay(polyline)
                complete(nil)
                return
            }
            
            complete(LocalizedString("network_error"))
        }
        
        return true
    }
    
    var coorSelf:CLLocationCoordinate2D {
        
        let coor = LocationManager.share.gcj02 ?? self.userLocation.coordinate
        
        return coor
    }
    
    private func removeAllOverlays() {
        
        self.removeOverlays(self.overlays)
    }
    
    func userMapCenter() {
        
        self.setCenter(self.userLocation.coordinate, animated: true)
    }
}

